/* FILE : clipboard.c */

#include <stdlib.h>
#include <string.h>

#include <gtk/gtk.h>
#include <gdk/gdkx.h>
#include "clipboard.h"

static void clipboard_get_handler(
		GtkClipboard *cb,
		GtkSelectionData *sel_data,
		guint info,
		gpointer data);

static GtkClipboard *status_clipboard = NULL;
static GtkClipboard *user_clipboard = NULL;
static ClipboardReceiveHandler *rec_handler = NULL;
void *send_buffer = NULL;
int send_length = 0;

#define TARGET_RAW_DATA			1
#define TARGET_CLIPBOARD_COMMAND	2

int
clipboard_init()
{
	GtkTargetEntry targets[2] = {
		{ RAW_DATA,		0,	TARGET_RAW_DATA},
		{ CLIPBOARD_COMMAND,	0,	TARGET_CLIPBOARD_COMMAND},
	};
	status_clipboard = gtk_clipboard_get(gdk_atom_intern(STATUS_CLIPBOARD, FALSE));
	user_clipboard = gtk_clipboard_get(gdk_atom_intern(STATUS_CLIPBOARD, FALSE));
	gtk_clipboard_set_with_data(user_clipboard, targets, 1,
			clipboard_get_handler, NULL, NULL);
	return 1;
}

void
clipboard_done()
{
	return;
}

void
clipboard_send(void *buffer, size_t size)
{
	GtkSelectionData *selection_data;

	send_buffer = malloc(size);
	memcpy(send_buffer, buffer, size);
	send_length = (int)size;

	selection_data = gtk_clipboard_wait_for_contents(status_clipboard,
			gdk_atom_intern(CLIPBOARD_COMMAND, FALSE));

	if (selection_data)
		gtk_selection_data_free(selection_data);
}

void
clipboard_set_receive_handler(ClipboardReceiveHandler *handler)
{
	rec_handler = handler;
}

static void
clipboard_get_handler(GtkClipboard *cb, GtkSelectionData *sel_data,
		guint info, gpointer data)
{
	//gchar *target = gdk_atom_name(sel_data->target);
	//guint num;
	//GList *l;
	//gchar **str_list = NULL;
	//gchar *final_str = NULL;
	//int i;

	switch (info) {
	case TARGET_RAW_DATA:
		gtk_selection_data_set(sel_data,
				gdk_atom_intern("UTF8_STRING", FALSE),
				8, (guchar*)send_buffer, send_length);
		free(send_buffer);
		send_buffer = NULL;
		send_length = 0;
		break;
	case TARGET_CLIPBOARD_COMMAND: {
		GtkSelectionData *selection_data;

		selection_data = gtk_clipboard_wait_for_contents(status_clipboard,
				gdk_atom_intern(RAW_DATA, FALSE));

		if (rec_handler) {
			(*rec_handler)(selection_data->data, (size_t)selection_data->length);
		} else {
#if DEBUG
			fprintf(stderr, "CLIPBOARD : have not set receive handler\n");
#endif
		}

		gtk_selection_data_free(selection_data);
		break;
	}
	} // switch
	//g_free(target);
}
